package fons.navigator;


import java.io.IOException;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.SwingUtilities;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;

import edu.umd.cs.piccolo.util.PDebug;
import fons.navigator.ui.NavigatorMainFrame;
import fons.navigator.ui.configurations.ConfigurationDialogLayoutBuilder;
import fons.navigator.ui.windows.messages.MessagesWindow;
import fons.navigator.util.SwingUtils;

public class NavigatorMain {
	public static boolean IS_OS_MAC = getOSMatches("Mac");
	public static final String OS_NAME = System.getProperty("os.name");
	private static NavigatorMainFrame mainFrame;
	
	private static final MessagesWindow messages = new MessagesWindow();
	private static final Logger logger = Logger.getLogger(NavigatorMain.class);
	
	static {
		BasicConfigurator.configure(messages);
	}
	
	public static void enableDebugging() {
		PDebug.debugThreads = true;
		PDebug.debugBounds = true;
		PDebug.debugFullBounds = true;
		PDebug.debugPaintCalls = false;//true;
		PDebug.debugPrintFrameRate = true;
		PDebug.debugPrintUsedMemory = true;
		PDebug.debugRegionManagement = true;
	}

	public static void main(String[] args) throws IOException {
		enableLogging();
		showMainFrame();
		logger.info("Navigator ist bereit");
	}

	private static void showMainFrame() {
		if (!IS_OS_MAC) {
			SwingUtils.initNimbusLF();
			
		}
		
		SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				(mainFrame = new NavigatorMainFrame()).setVisible(true);
				ConfigurationDialogLayoutBuilder.load();
			}	
		});
	}

	private static boolean getOSMatches(String osNamePrefix) {
		if (OS_NAME == null) {
			return false;
		}
		return OS_NAME.startsWith(osNamePrefix);
	}

	public static ImageIcon createImageIcon(String path) {
		URL url = NavigatorMain.class.getResource(path);
		if (url != null) {
			return new ImageIcon(url);
		} else {
			logger.error("Datei \"" + path + "\" konnte nicht gefunden werden");
			return null;
		}
	}

	public static NavigatorMainFrame getMainFrame() {
		return mainFrame;
	}
	
	private static void enableLogging() {
		messages.setLayout(new PatternLayout("<tr>" +
				"<td class=\"time\"><span class=\"%p\">%d{HH:mm:ss}</span></td>" +
				"<td class=\"level\"><span class=\"%p\">%p</span></td>" +
				"<td class=\"message\"><span class=\"%p\">%m</span></td></tr>"));
	}
	
	public static MessagesWindow getMessagesWindow() {
		return messages;
	}
}